package homework3.com.qianfeng.cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class MyBeanFactory {
	public static UserServiceImpl createUserService() {
		UserServiceImpl userService = new UserServiceImpl();
		TransactionManager transactionManager = new TransactionManager();
		Enhancer en = new Enhancer();
		en.setSuperclass(userService.getClass());
		en.setCallback(new MethodInterceptor() {
			
			@Override
			public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
				Object returnVal = null;
				try {
					transactionManager.beginTransaction();
					returnVal = method.invoke(userService, args);
					transactionManager.commit();
				} catch(Exception e) {
					transactionManager.rollback();
				} finally {
					transactionManager.release();
				}
				return returnVal;
			}
		});
		UserServiceImpl userServiceProxy = (UserServiceImpl) en.create();
		return userServiceProxy;
	}
}
